<?php
namespace App\Logic\SalesReport;

use App\Models\Basics\AmazonCountry;
use App\Models\Basics\ExchangeRate;
use App\Models\Product\ProductAmazonSku;
use App\Models\MonthlyReport\Payment\CommonFee;
use App\Models\MonthlyReport\Cost\LogisticsBasics;
use App\Models\MonthlyReportCommon\Cost\PriceBasics;
use App\Models\SalesReport\PaymentDetail as TPaymentDetail;
use Illuminate\Support\Facades\DB;
class PaymentDetailCommon
{
    public static function exePayment($date){
        try{
            DB::beginTransaction();
            $purchasePrice = [];
            $shipmentPrice = [];
            CommonFee::where('report_date',$date)
                ->orderBy('id')
                ->chunk(100, function ($sfs) use (&$purchasePrice,&$shipmentPrice,$date){
                    foreach ($sfs as $sf){
                        if(!$sf->area_id)continue;
                        $where = [];
                        $where['report_date'] = $sf->report_date;
                        $where['account_id'] = $sf->account_id;
                        $where['area_id'] = $sf->area_id;
                        $where['country_id'] = $sf->country_id;
                        $where['seller_id'] = 0;
                        $where['seller_sku'] = $sf->seller_sku;
                        $paymentDetail = [];
                        if($sf->country_id){
                            $currencyCode = AmazonCountry::getCurrencyCodeByCountryId($sf->country_id);
                        }else{
                            if($sf->area_id == 4){
                                $currencyCode = 'EUR';
                            }else{
                                continue;
                            }
                        }
                        if(!is_numeric($sf->seller_sku) || (is_numeric($sf->seller_sku) && intval($sf->seller_sku) != 0)){
                            $paymentDetail['psku_id'] = self::_getPSkuId($sf->seller_sku);
                        }
                        if(isset($paymentDetail['psku_id']) && $paymentDetail['psku_id']){
                            $priceKey = $paymentDetail['psku_id'].'-'.$date;
                            if(!array_key_exists($priceKey,$purchasePrice)){
                                $purchasePrice[$priceKey] = PriceBasics::getPrice($paymentDetail['psku_id'],$date);
                            }
                            $paymentDetail['purchase_price_rmb'] = $purchasePrice[$priceKey];
                            $lPriceKey = $sf->area_id.'-'.$paymentDetail['psku_id'].'-'.$date;
                            if(!array_key_exists($lPriceKey,$shipmentPrice)){
                                $shipmentPrice[$lPriceKey] = LogisticsBasics::getLogistics($sf->area_id,$paymentDetail['psku_id'],$date);
                            }
                            $paymentDetail['shipment_price_rmb'] = $shipmentPrice[$lPriceKey];
                        }
                        $rateOdds = ExchangeRate::getRateOddsToRMB($currencyCode,strtotime($sf->report_date));
                        $paymentDetail['rate_odds'] = $rateOdds;
                        $paymentDetail['selling_fees'] = $sf->selling_fees ?: 0;
                        $paymentDetail['selling_fees_rmb'] = round($paymentDetail['selling_fees'] * $rateOdds,3);
                        $paymentDetail['p_thfba'] = $sf->thfba ?: 0;
                        $paymentDetail['p_thfba_rmb'] = round($paymentDetail['p_thfba'] * $rateOdds,3);
                        $paymentDetail['p_icfee'] = $sf->ic_fee ?: 0;
                        $paymentDetail['p_icfee_rmb'] = round($paymentDetail['p_icfee'] * $rateOdds,3);
                        $paymentDetail['ms_fee'] = $sf->ms_fee ?: 0;
                        $paymentDetail['ms_fee_rmb'] = round($paymentDetail['ms_fee'] * $rateOdds,4);
                        $paymentDetail['lts_fee'] = $sf->lts_fee ?: 0;
                        $paymentDetail['lts_fee_rmb'] = round($paymentDetail['lts_fee'] * $rateOdds,3);
                        $paymentDetail['rm_fee'] = $sf->rm_fee ?: 0;
                        $paymentDetail['rm_fee_rmb'] = round($paymentDetail['rm_fee'] * $rateOdds,3);
                        $paymentDetail['rebates'] = $sf->rebates ?: 0;
                        $paymentDetail['rebates_rmb'] = round($paymentDetail['rebates'] * $rateOdds,3);
                        $paymentDetail['fba_fees'] = $sf->fba_fees ?: 0;
                        $paymentDetail['fba_fees_rmb'] = round($paymentDetail['fba_fees'] * $rateOdds,3);
                        $paymentDetail['sales_volume'] = $sf->sales_volume ?: 0;
                        $paymentDetail['sales_amount'] = $sf->sales_amount ?: 0;
                        $paymentDetail['sales_amount_rmb'] = round($paymentDetail['sales_amount'] * $rateOdds,3);
                        $paymentDetail['refund_num'] = $sf->refund_num ?: 0;
                        $paymentDetail['refund_amount'] = $sf->refund_amount ?: 0;
                        $paymentDetail['refund_amount_rmb'] = round($paymentDetail['refund_amount'] * $rateOdds,3);
                        $paymentDetail['spend'] = $sf->spend ?: 0;
                        $paymentDetail['spend_rmb'] = round($paymentDetail['spend'] * $rateOdds,3);
                        $paymentDetail['reimburse_os_rmb'] = $sf->reimburse_os_rmb ?: 0;
                        $paymentDetail['ied_rmb'] = $sf->ied_rmb ?: 0;
                        $paymentDetail['rod_rmb'] = $sf->rod_rmb ?: 0;
                        $paymentDetail['vat_fee'] = $sf->vat_fee ?: 0;
                        $paymentDetail['vat_fee_rmb'] = round($paymentDetail['vat_fee'] * $rateOdds,3);
                        $paymentDetail['cplan_fee'] = $sf->cplan_fee ?? 0;
                        $paymentDetail['cplan_fee_rmb'] = round($paymentDetail['cplan_fee'] * $rateOdds,3);
                        $paymentDetail['total'] = $sf->total ?: 0;
                        $paymentDetail['total_rmb'] = round($paymentDetail['total'] * $rateOdds,3);
                        $paymentDetail['t_purchase_price_rmb'] = round($paymentDetail['sales_volume'] * ($paymentDetail['purchase_price_rmb'] ?? 0),3);
                        $paymentDetail['t_shipment_price_rmb'] = round($paymentDetail['sales_volume'] * ($paymentDetail['shipment_price_rmb'] ?? 0),3);
                        $paymentDetail['profit_rmb'] = round($paymentDetail['sales_amount_rmb'] +
                            $paymentDetail['ied_rmb'] +
                            $paymentDetail['selling_fees_rmb'] +
                            $paymentDetail['refund_amount_rmb'] +
                            $paymentDetail['p_thfba_rmb'] +
                            $paymentDetail['p_icfee_rmb'] -
                            $paymentDetail['ms_fee_rmb'] -
                            $paymentDetail['lts_fee_rmb'] -
                            $paymentDetail['rm_fee_rmb'] +
                            $paymentDetail['rebates_rmb'] +
                            $paymentDetail['fba_fees_rmb'] -
                            $paymentDetail['spend_rmb'] -
                            $paymentDetail['rod_rmb'] -
                            $paymentDetail['reimburse_os_rmb'] +
                            $paymentDetail['cplan_fee_rmb'] -
                            $paymentDetail['vat_fee_rmb'],3);
                        $paymentDetail['earning_rmb'] = round($paymentDetail['t_purchase_price_rmb'] +
                            $paymentDetail['t_shipment_price_rmb'] +
                            $paymentDetail['profit_rmb'],3);
                        $paymentDetail['is_common'] = 1;
                        TPaymentDetail::updateOrCreate($where,$paymentDetail);
                    }
                });
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
        }
    }

    private static function _getPSkuId($selleSku){
        $pas = ProductAmazonSku::where('seller_sku',$selleSku)
            ->orderBy('id')
            ->first();
        return $pas ? $pas->psku_id : 0;
    }
}
